package com.atguigu.tingshu.common.config;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

@Configuration
@Slf4j
public class RabbitConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        // 确认消息是否到达交换机，不管有没有到达交换机都会执行
        this.rabbitTemplate.setConfirmCallback((@Nullable CorrelationData correlationData, boolean ack, @Nullable String cause) -> {
            if (!ack){
                // 输出日志，或者记录到redis，将来进行重试
                if (correlationData != null){
                    ReturnedMessage returned = correlationData.getReturned();
                    log.error("消息id为{}的消息没有到达交换机：{}，消息的内容：{}", correlationData.getId(), cause, new String(returned.getMessage().getBody()));
                } else {
                    log.error("没有到达交换机：{}", cause);
                }
            }
        });
        // 确认消息是否到达队列，只有没有到达队列时才会执行
        this.rabbitTemplate.setReturnsCallback((ReturnedMessage returned) -> {
            log.error("消息没有到达队列。交换机：{}，路由键：{}，消息内容：{}，回调状态：{}，回调文本：{}",
                    returned.getExchange(), returned.getRoutingKey(), new String(returned.getMessage().getBody()),
                    returned.getReplyCode(), returned.getReplyText());
        });
    }
}
